package com.mb;

import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;

import com.dao.SingularDAO;
import com.facade.UserFacade;
import com.model.Singular;
import com.model.User;

@RequestScoped
@ManagedBean
public class LoginMB extends AbstractMB {
	@ManagedProperty(value = UserMB.INJECTION_NAME)
	private UserMB userMB;
	private SingularDAO singularDAO = new SingularDAO();

	private String login;
	private String password;

	private List<Singular> singulares;

	private Singular singularSelecionada;

	/*
	 * public LoginMB() { singularDAO.beginTransaction(); singulares =
	 * singularDAO.getAll(Singular.FIND_ALL); }
	 */

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	/*
	 * public List<Singular> getSingulares() { singularDAO.beginTransaction();
	 * singulares = singularDAO.getAll(Singular.FIND_ALL);
	 * 
	 * return singulares; }
	 */
	public List<SelectItem> getSingulares() {
		singularDAO.beginTransaction();
		singulares = singularDAO.getAll(Singular.FIND_ALL);

		List<SelectItem> itens = new ArrayList<SelectItem>(singulares.size());

		for (Singular sing : singulares) {
			itens.add(new SelectItem(sing.getNome(), sing.getNome()));
		}
		return itens;
	}

	public Singular getSingularSelecionada() {
		return singularSelecionada;
	}

	public void setSingularSelecionada(Singular singularSelecionada) {
		this.singularSelecionada = singularSelecionada;
	}

	public String login() {
		UserFacade userFacade = new UserFacade();

		User user = userFacade.isValidLogin(login, password,
				singularSelecionada);

		if (user != null) {
			userMB.setUser(user);
			FacesContext context = FacesContext.getCurrentInstance();
			HttpServletRequest request = (HttpServletRequest) context
					.getExternalContext().getRequest();
			request.getSession().setAttribute("user", user);
			return "/pages/protected/index.xhtml";
		}

		displayErrorMessageToUser("Verifique seu login/senha");

		return null;
	}

	public void setUserMB(UserMB userMB) {
		this.userMB = userMB;
	}
}